//
//  CourseListViewController.swift
//  TalkeTv
//
//  Created by lhf on 2024/9/20.
//

import UIKit
import SwiftyJSON
import Toast_Swift
import Alamofire
import AlamofireImage

class CourseListViewController: BaseViewController,UITableViewDataSource,UITableViewDelegate {

    var searchKey: String?
    
    @IBOutlet weak var emptyBgView: EmptyView!
    
    @IBOutlet weak var courseTableView: UITableView!
    var courseArr = JSON.init(parseJSON: "[]")
    var page = 1
    
    // MARK: UITableViewDelegate
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return courseArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell:UITableViewCell! = tableView.dequeueReusableCell(withIdentifier: "courseCell")
        cell.selectionStyle = UITableViewCell.SelectionStyle.none
        
        let item = courseArr[indexPath.row]
        let cover = cell?.viewWithTag(1) as! UIImageView
        let coverImageUrl = item["cover"].stringValue.imageSizeToThumbnail(contentView: cover)
        print("课程列表图片url：\(coverImageUrl)")
        cover.af.setImage(withURL: URL(string: coverImageUrl)!, placeholderImage: UIImage.init(named: "logo"))
        let name = cell?.viewWithTag(2) as! UILabel
        name.text = item["name"].stringValue
        let remark = cell?.viewWithTag(3) as! UILabel
        remark.text = item["remark"].stringValue
        let time = cell?.viewWithTag(4) as! UILabel
        time.text = item["lastModifiedDate"].stringValue.components(separatedBy: " ")[0]
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let courseDetail = UtilManager.sharedInstance.getVCFromSB(identifier: "CourseDetailViewController") as! CourseDetailViewController
        courseDetail.courseId = courseArr[indexPath.row].dictionaryObject!["id"] as! String
        self.navigationController?.pushViewController(courseDetail, animated: true)
    }
    
    func handleGetData() {
        var params = JSON.init(parseJSON: "{}")
        params["page"].string = String(page)
        params["size"].string = "10"
        if let searchKey {
            params["name"].string = searchKey
        }
        
        APIManager.sharedInstance.sendRequest(urlString: APIManager.sharedInstance.course_list_action, method: HTTPMethod.get, params: params) { (result, error) in
            if error == nil {
                if self.page == 1 {
                    self.courseArr = result["data"]["list"]
                    self.courseTableView.mj_header?.endRefreshing()
                } else {
                    
                    var list = self.courseArr.arrayValue
                    for (_, item) in result["data"]["list"] {
                        list.append(item)
                    }
                    self.courseArr = JSON.init(list)
                    self.courseTableView.mj_footer?.endRefreshing()
                }
                
                if result["data"]["list"].arrayValue.count < 10 {
                    self.courseTableView.mj_footer?.endRefreshingWithNoMoreData()
                } else {
                    self.courseTableView.mj_footer?.endRefreshing()
                }
                
                self.courseTableView.reloadData()
                
                self.courseTableView.isHidden = self.courseArr.count == 0
                self.emptyBgView.isHidden = self.courseArr.count != 0
            }
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        courseTableView.estimatedRowHeight = 145.0
        courseTableView.rowHeight = UITableView.automaticDimension
        courseTableView.tableFooterView = UIView.init()
        
        courseTableView.mj_header = MJRefreshNormalHeader.init {[weak self] in
            self?.page = 1
            self?.handleGetData()
        }
        courseTableView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {[weak self] in
            self?.page = self!.page + 1
            self?.handleGetData()
        })
        
        handleGetData()
        // Do any additional setup after loading the view.
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
